package edu.hda.pt.server.connections.xsocket;

import java.io.IOException;
import java.nio.BufferOverflowException;
import java.util.Vector;

import org.xsocket.connection.INonBlockingConnection;
import org.xsocket.connection.IConnection.FlushMode;

/**
 * Thread for managing the streams
 * 
 * @author Marc Hammerton
 * 
 */
public class StreamThread extends Thread {

	private Vector<INonBlockingConnection> connections = new Vector<INonBlockingConnection>();

	private int fileSize = 0;

	/**
	 * Sets the file size which should be sent to the client
	 * 
	 * @param fileSize
	 *            - the fileSize to set
	 */
	public void setFileSize(int fileSize) {
		this.fileSize = fileSize;
	}

	/**
	 * Returns the file size
	 * 
	 * @return the file size
	 */
	public int getFileSize() {
		return fileSize;
	}

	/**
	 * Adds a new connection
	 * 
	 * @param connection
	 *            - the connection to be added
	 */
	public void addConnection(INonBlockingConnection connection) {
		this.connections.add(connection);
	}

	/**
	 * Removes an existing connection
	 * 
	 * @param connection
	 *            - the connection to be removed
	 */
	public void removeConnection(INonBlockingConnection connection) {
		this.connections.remove(connection);
	}

	/**
	 * While the thread is not interrupted, it checks if a connection exists. In
	 * this case, it sends a message of the size fileSize to the client. If no
	 * connection exists, it waits until it is notified.
	 */
	@Override
	public void run() {
		byte[] data = null;
		while (!isInterrupted()) {
			if (connections.size() == 0) {
				this.fileSize = 0;
				try {
					synchronized (this) {
						this.wait();
					}

				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			} else {

				synchronized (connections) {
					data = new byte[this.fileSize];
					for (INonBlockingConnection connection : connections) {
						connection.setFlushmode(FlushMode.SYNC);
						if (connection.isOpen()) {
							try {
								// connection.write(data.length);
								connection.write(data);
								connection.flush();
							} catch (BufferOverflowException e) {
								e.printStackTrace();
							} catch (IOException e) {
								e.printStackTrace();
							}

						} else {
							interrupt();
						}
					}

				}
			}
		}

	}

	/**
	 * @see java.lang.Thread#interrupt()
	 */
	@Override
	public void interrupt() {
		super.interrupt();
	}
}
